<template>
  <view class="cart-shop">
      <view class="side-b">
		  <u-toast ref="uToast" />
		  <u-modal v-model="modalShow" :content="content" :show-title='false' @cancel="cancelPay"
		  :confirm-text='confirmText' :cancel-text='cancelText' :show-cancel-button='true'
		  @confirm="goPay"></u-modal>
        <scroll-view
            id="side_b"
            scroll-y
            class="side-scroll"
            :scroll-with-animation="scrollWithAnimation"
            style="height: 100%"
            :scroll-into-view="intoView"
            @scroll="contentScroll"
        >
			<view class="item" v-for="ite in data" :key="ite.id">
			    <view class="img-box">
			        <image :src="ite.logo" class="img"></image>
			    </view>
			    <view class="goods-info">
			        <view class="title">{{ ite.name }}</view>
			        <view class="description">{{ ite.description }}</view>
			        <!-- <view class="num">月售{{ item.monthlySales }}</view> -->
			        <view class="price">
			            <view>
			                <text class="ite-price">￥{{ ite.price }}</text>
			                <text class="unit">/份</text>
			            </view>
						<text>共 {{ite.goodNum}} 份</text>
						<text>￥{{ite.goodNum * ite.price}}</text>
			            <!-- <NumerCalculation @change="(val)=>numberCalculationAction(val,ite,item)"/> -->
			        </view>
			    </view> 
			</view>
        </scroll-view>
      </view>
	<view class="shopping-buttom"  v-if="data.length != 0">
		
		<view class="shopping-total" style="background-color: rgba(255, 255, 255, 0.75);">
			<text>共{{num}}件</text>
			<text>总价:<text>￥{{this.sutotal}}</text></text>
		</view>
		<u-button type="success" @click="submitShopping">提交订单</u-button>
	</view>
	<view class="shopping-empty"  v-if="data.length == 0">
		<view class="">购物车空空如也</view>
		<view class="">快选择宝贝加入吧</view>
	</view>
  </view>
</template>

<script>
	import { submitOrder, submitPay } from '@/api/system/shop/shop'
export default {
    props:{
      data:{
          type:Array,
          default:()=>[]
      },
      columns:{
          type:Array,
          default:()=>[]
      },
      // 点击侧边栏 右边是否需要动画
      scrollWithAnimation:{
          type:Boolean,
          default:true
      }
    },
    data() {
        return {
			modalShow: false,
			orderId: '',
			content: '订单提交成功，请及时支付',
			confirmText: '去支付',
			cancelText: '取消',
            intoView:'v_0',
            sideCurrentIndex:0,
            scrollTop:0,
            contentHeightArr:[],
            handleSideClick:true,
			sutotal: 0,
			num: 0
        }
    },
    mounted(){
        this.getContentHeight()
		console.log(this.data)
		this.sutotal = this.$store.getters.subtotal
		this.getSutotal()
    },
	onShow() {
	},
    methods:{
		submitShopping(){
			const addressId = this.$store.getters.addrId
			const tableId = this.$store.getters.table
			const shoppingCartList = this.$store.getters.shoppingCart
			// const user = this.$store.getters.name
			
			var submitData = {
				tableId,
				addressId,
				shoppingCartList,
			}
			// if (this.$store.getters.dineStyle=='外卖'){
			// 	const addrId = this.$store.getters.addrId
			// 	submitData = {
			// 		addrId,
			// 		shoppingCartList,
			// 		// user
			// 	}
			// } else if (this.$store.getters.dineStyle=='堂食'){
			// 	const tableId = this.$store.getters.table
			// 	submitData = {
			// 		tableId,
			// 		shoppingCartList,
			// 		// user
			// 	}
			// }
			console.log(submitData)
			submitOrder(submitData).then(res=>{
				console.log(res)
				if(res.code === 200){
					// this.$refs.uToast.show({
					// 	title: '订单提交成功，请及时支付',
					// 	type: 'success',
					// })
					this.orderId = res.msg;
					// 清空vuex中购物车
					this.$store.dispatch('updateShoppingCart',[])
				
					this.modalShow = true
				}
			})
		},
		// 暂不支付
		cancelPay(){
			this.$refs.uToast.show({
				title: '订单提交成功，请尽快完成支付',
				type: 'warning'
			})
			this.$tab.reLaunch('/pages/shop/shop')
			// setTimeout(()=>{
			// 	// uni.reLaunch({
			// 	// 	url: '/pages/shop/shop'
			// 	// })
			// 	this.$tab.reLaunch('/pages/shop/shop')
			// },1000)
		},
		// 去支付
		goPay(){
			const payData = {
				"orderId":this.orderId
				}
			submitPay(payData).then(res=>{
				console.log(res)
				if(res.code === 200){
					this.$refs.uToast.show({
						title: '支付成功',
						type: 'success',
					})
					setTimeout(function(){
						uni.reLaunch({
							url: '/pages/shop/shop'
						})
					},2000)
				}
			})
			
		},
		getSutotal(){
			for (const item of this.data) {
				console.log(item)
			  this.num += item.goodNum;
			}
		},
        numberCalculationAction(val,item,ite){
            this.$emit('numberComputed',val,item,ite)

        },
        getContentHeight(){
            this.getHeight('.item_b').then(res=>{
                res.forEach((item,index)=>{
                    let top = index > 0 ? this.contentHeightArr[index - 1] : 0;
                    top += item.height;
                    this.contentHeightArr.push(top)
                })
            })
        },
        async getHeight(element) {
            return new Promise((resolve) => {
                let view = uni.createSelectorQuery().in(this).selectAll(element);
                view.boundingClientRect(data => {
                    if(!data){
                        setTimeout(()=>{
                            this.getHeight()
                        },10)
                        return
                    }
                    resolve(data)
                }).exec();
            })
        },
        contentScroll(event){
            let scrollTop = event.target.scrollTop
            let index = this.contentHeightArr.findIndex((item)=>{
                return scrollTop<=item
            })
            if(!this.handleSideClick){
                this.sideCurrent = index<0?this.sideCurrent:index;
            }
            this.scrollHeight()
        },
        handleSideAction(item,index){
            this.handleSideClick = true
            this.sideCurrentIndex = index
            this.intoView = `v_${index}`
            this.scrollHeight()
            setTimeout(()=>{
                this.handleSideClick = false
            },300)
        },
        async getWrapSideHeight() {
            return new Promise(resolve => {
                let view = uni.createSelectorQuery().in(this).select(".side-a");
                view.boundingClientRect(data => {
                    resolve(data)
                }).exec();
            })
        },
        async scrollTopTo(OffsetHeight, itemTab) {
            let tabNav = await this.getWrapSideHeight()
            this.scrollTop = OffsetHeight - (tabNav.height - itemTab.height) / 2
        },
        async scrollHeight() {
            let tabs = await this.getHeight(".side-item")
            let itemTab = tabs[this.sideCurrentIndex]
            if (!itemTab) return

            let currentBeforeArr = tabs
                .slice(0, this.sideCurrentIndex)

            let OffsetHeight = currentBeforeArr
                .reduce((total, curr) => {
                    return total + curr.height
                }, 0);
            this.scrollTopTo(OffsetHeight,itemTab)

        },
    }
}
</script>


<style lang="scss" scoped>
	.shopping-total{
		margin-bottom: 3px;
		text{
			margin-left: 5px;
			margin-right: 5px;
		}
	}
	.shopping-buttom{
		  position: fixed;
		  left: 50%;
		  bottom: 0;
		  transform: translateX(-50%);
		  padding-bottom: 10px;
	}
	.shopping-empty{
		  position: fixed;
		  top: 50%;
		  left: 50%;
		  transform: translate(-50%, -50%);
		  font-size: 20px;
			text-align: center;
	}
.cart-shop{
  display: flex;
  flex: 1;
  overflow: hidden;
}
.side-scroll{
  position: relative;
}
.side_b_title{
    position: sticky;
    top: -2rpx;
    left: 0;
    z-index: 99;
    padding: 10rpx 24rpx;

    background: white;
}
.badge{
    right: -2rpx;
    top: -2rpx;
    background-color: #9E2A22;
    position: absolute;
    display: flex;
    overflow: hidden;
    box-sizing: border-box;
    justify-content: center;
    flex-direction: row;
    height: 20px;
    min-width: 20px;
    padding: 0 4px;
    line-height: 18px;
    color: #fff;
    border-radius: 100px;
    border: 1px solid #fff;
    text-align: center;
    font-family: Helvetica Neue,Helvetica,sans-serif;
    -webkit-font-feature-settings: "tnum";
    font-feature-settings: "tnum";
    font-size: 12px;
    z-index: 9;
    cursor: pointer;
}
.side-item{
    position: relative;
}
.side-b{
	position: relative;
	padding-top: 20px;
    flex: 1;
    background: white;
    padding-bottom: 20rpx;
    box-sizing: border-box;
  .goods{
    font-size: 26rpx;

  }
  .country{
    font-size: 22rpx;
    color: #999999;
  }
  .item{
    padding: 0 30rpx;
    display: flex;
    .img-box{
      width: 140rpx;
      height: 140rpx;
      margin-right: 15rpx;
      .img{
        width: 75%;
        height: 75%;
        border-radius: 8rpx;
      }
    }
    .goods-info{
      flex: 1;
    }
    .title{
      font-size: 26rpx;
      margin-bottom: 8rpx;
      font-weight: bold;
    }
    .num{
      color: #999999;
      font-size: 22rpx;
    }
    .description{
      font-size: 22rpx;
      color: #666666;
      margin-bottom: 16rpx;
    }
    .price{
      display: flex;
      align-items: center;
      justify-content: space-between;
      .item-price{
        font-size: 32rpx;
      }
      .unit{
        color: #999999;
        font-size: 22rpx;
      }
    }
  }
}
.text-ellipsis__2 {
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
</style>